using System;
using System.Collections.Generic;
using System.Text;

namespace VG.EAP.Common
{
    public class JsResult
    {
        private IDictionary<string, object> _attributes = new Dictionary<string, object>();
        private bool _isSuccess = true;
        private string _errorMessage = string.Empty;

        public JsResult(string errorMessage)
        {
            this._isSuccess = false;
            this._errorMessage = errorMessage;
        }
        public JsResult()
        {
        }

        public JsResult AddAttr(string name, object value)
        {
            this._attributes.Add(name, value);
            return this;
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            if (this._isSuccess) sb.Append("result:true,");
            else
                sb.Append("result:false,exception:\"").Append(this._errorMessage).Append('"').Append(',');

            foreach (KeyValuePair<string, object> kv in this._attributes)
            {
                sb.Append(kv.Key).Append(":");
                if (kv.Value == null)
                {
                    sb.Append("null").Append(',');
                    continue;
                }
                switch (kv.Value.GetType().Name)
                {
                    case "Int32":
                    case "Decimal":
                    case "Single":
                    case "Double":
                        sb.Append(kv.Value);
                        break;
                    case "Boolean":
                        bool bv = (bool)kv.Value;
                        sb.Append(bv ? "true" : "false");
                        break;
                    case "DateTime":
                        DateTime dtv = (DateTime)kv.Value;
                        if (dtv.Hour > 0 || dtv.Minute > 0) sb.Append('"').Append(dtv.ToString("yyyy-MM-dd HH:mm:ss")).Append('"');
                        else sb.Append('"').Append(dtv.ToString("yyyy-MM-dd")).Append('"');
                        break;
                    default:
                        sb.Append('"')
                            .Append(kv.Value.ToString().Replace("\"", "\\\"")).Replace('\r', default(char)).Replace('\n', default(char))
                            .Append('"');
                        break;
                }
                sb.Append(',');
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("}");
            return sb.ToString();
        }
    }
}
